import React from 'react';
import { Layout, Card, Row, Col, Typography, Spin } from 'antd';
import { useRequest } from 'ahooks';
import { SvgIcon } from '@/components/icon';
import useWindowWidth from '@/hooks/event/use-window-width';
import metahumanService from '@/api/services/metahumanService';
import { MetahumanResource } from '@/types/metahuman';
import ApplicationCard from './application-card';
import './metahuman.css';

const { Content } = Layout;
const { Title, Text } = Typography;

interface ApplicationCard {
  id: string;
  name: string;
  description: string;
  connectionStatus?: string;
  icon: string;
}

const MetahumanUsage: React.FC = () => {

  const defaultApplications: ApplicationCard[] = [];

  // 使用 useRequest 管理API请求
  const { data: connectionData, loading, error, run } = useRequest(
    async () => {
      const response = await metahumanService.getMetahumanConnectionStatus();
      return response.resources;
    },
    {
      manual: false,
      onError: (error) => {
        console.error('获取数字人连接状态失败:', error);
      }
    }
  );

  // 处理数据转换
  const getUsageApplications = (): ApplicationCard[] => {
    console.log('connectionData', connectionData);

    // 如果API请求失败或没有数据，使用默认数据
    if (error || !connectionData) {
      return defaultApplications;
    }

    // 将API数据转换为组件需要的格式
    return connectionData.map((resource: MetahumanResource, index: number) => ({
      id: resource.appId,
      name: resource.appName,
      description: resource.appDescription,
      connectionStatus: `${resource.activeConnections}/${resource.maxConnections}`,
      icon: resource.appAvatar
    }));
  };

  const usageApplications = getUsageApplications();

  if (loading) {
    return (
      <Layout style={{ background: 'transparent' }}>
        <Content style={{ padding: '0px', textAlign: 'center', paddingTop: '50px' }}>
          <Spin size="large" />
        </Content>
      </Layout>
    );
  }

  return (
    <Layout style={{ background: 'transparent' }}>
      <Content style={{ padding: '0px' }}>
        <div style={{ 
          background: '#F8F9FA', 
          padding: '16px', 
          borderRadius: '12px', 
          marginBottom: '24px',
          border: '1px solid #E5E6EB'
        }}>
          <Text style={{ fontSize: '16px', color: '#1D1E51', fontWeight: '500' }}>
            {usageApplications.length === 0 ? '暂无应用正在使用数字人' : `${usageApplications.length}个应用正在使用数字人`}
          </Text>
        </div>
        <Row gutter={[16, 16]}>
          {usageApplications.map((app) => (
            <Col key={app.id} xs={24} sm={12} md={8} lg={8} xl={8}>
              <ApplicationCard
                id={app.id}
                name={app.name}
                description={app.description}
                connectionStatus={app.connectionStatus}
                icon={app.icon}
                isPreview={true}
              />
            </Col>
          ))}
        </Row>
      </Content>
    </Layout>
  );
};

export default MetahumanUsage; 